<?php

class GoogleService extends Auth
{
    public $clientId='';
    public $clientSecret='';
    protected $token='';
    protected $userInfo=false, $serviceName='google';

    public function getUserInfo()
    {
        $info=$this->userInfo;

        return array(
            'user'=>array(
                'login'=>isset($info->uid) ? $info->uid : '',
                'userName'=>isset($info->uid) ? $info->uid : '',
                'password'=>'',
                'confirmCode'=>'',
                'email'=>isset($info->email) ? $info->email : '',
                'isConfirmed'=>1,
                'isActive'=>isset($info->is_verified) ? $info->is_verified : 0,
            ),
            'profile'=>array(
                'firstName'=>isset($info->first_name) ? $info->first_name : '',
                'lastName'=>isset($info->last_name) ? $info->last_name : '',
                'sex'=>$info->sex!=0 ? 1 : 0,
                'img'=>isset($info->has_pic) ? $info->pic : '',
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $requestUrl='https://accounts.google.com/o/oauth2/auth?redirect_uri='.$this->getReturnUrl().
            '/&response_type=code&client_id='.$this->clientId.
            '&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile';

        Yii::app()->request->redirect($requestUrl);
    }

    public function secondRequest()
    {
        if($code=Yii::app()->request->getQuery('code')){
            try{
                $bodyParams='code='.$code.
                    '&client_id='.$this->clientId.
                    '&client_secret='.$this->clientSecret.
                    '&redirect_uri='.$this->getReturnUrl().
                    '&grant_type=authorization_code';

                $msg="POST /o/oauth2/token HTTP/1.1\r\nHost: accounts.google.com\r\nContent-type: application/x-www-form-urlencoded\r\nContent-Length: ".
                    (strlen($bodyParams))."\r\n\r\n".$bodyParams."\r\n\r\n";

                $socket=fsockopen('ssl://accounts.google.com',443);
                fwrite($socket,$msg);

                $answer='';
                while(!feof($socket)){
                    $answer.=fgets($socket,4098);
                };
                fclose($socket);

                if($pos=strpos($answer,'{')){
                    $answer=substr($answer,$pos);
                    $strParts=explode(',',str_replace('{','',str_replace('}','',$answer)));


                    foreach($strParts as $str){
                        $str=str_replace('"','',$str);
                        if($parts=explode(':',$str)){
                            foreach($parts as $num=>$part){
                                if($part=='access_token'){
                                    $this->token=$parts[$num+1];
                                    break;
                                }
                            }
                            if($this->token) break;
                        }
                    }
                }

                if($this->token){
                    $redirectUrl='https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$this->token;

                    if(is_object($result=json_decode(file_get_contents($redirectUrl)))){
                        if(isset($result->error_msg)) $this->quit($result->error_msg);
                        $this->userInfo=$result;
                        return true;
                    }
                }
            }catch(Exception $e){
                $this->quit($e);
            }
        }

        return false;
    }
}